#include "StickyNote.h"
#include <QPainter>
#include "Tools.h"
#include <QClipboard>
#include <QFileDialog>
#include <QApplication>
#include <QCursor>

StickyNote::StickyNote(const QImage& image, QWidget *parent) : QWidget(parent), image(image)
{
    setWindowFlags(Qt::ToolTip | Qt::WindowStaysOnTopHint | Qt::FramelessWindowHint);
    setFixedSize(image.size());
    setFocusPolicy(Qt::StrongFocus);

    show();
    activateWindow();
    setFocus();

    tools = new Tools;
    tools->setTack();

    initToolConnect();
}

StickyNote::~StickyNote()
{
    delete tools;
}

QImage StickyNote::getScreenShotImage()
{
    return image;
}

void StickyNote::initToolConnect()
{
    connect(tools, &Tools::download, [this]{
        QString filename = QFileDialog::getSaveFileName(nullptr, "保存", "未命名.jpg", "(*.jpg);;(*.png)");
        if(filename.isEmpty()) return;
        getScreenShotImage().save(filename);
    });
    connect(tools, &Tools::clipBoard, [this]{
        QClipboard* clipBoard = qApp->clipboard();
        clipBoard->setImage(getScreenShotImage());
    });
    connect(tools, &Tools::finished, this, &StickyNote::deleteLater);
}

void StickyNote::clearTimer()
{
    if(timerId != -1){
        killTimer(timerId);
        timerId = -1;
    }
    setFocus();
}

void StickyNote::paintEvent(QPaintEvent *)
{
    QPainter painter(this);
    painter.setPen(Qt::NoPen);
    painter.drawImage(rect(), image);
}

void StickyNote::mousePressEvent(QMouseEvent *)
{
    pressedPoint = QCursor::pos();
}

void StickyNote::mouseMoveEvent(QMouseEvent *)
{
    QPoint point = QCursor::pos();
    move(pos() - pressedPoint + point);
    pressedPoint = point;
    tools->set(geometry());
}

void StickyNote::mouseReleaseEvent(QMouseEvent *)
{
    tools->set(geometry());
}

void StickyNote::focusInEvent(QFocusEvent *)
{
    clearTimer();
}

void StickyNote::focusOutEvent(QFocusEvent *)
{
    timerId = startTimer(300);
}

void StickyNote::timerEvent(QTimerEvent *)
{
    tools->unset();
}
